// CameraManager 类
class CameraManager {
    constructor(videoElement, cameraSelect) {
        this.videoElement = videoElement;
        this.cameraSelect = cameraSelect;
        this.stream = null;
        this.devices = [];
    }

    async init() {
        try {
            // 获取所有视频设备
            const devices = await navigator.mediaDevices.enumerateDevices();
            this.devices = devices.filter(device => device.kind === 'videoinput');
            
            // 清空并填充摄像头选择下拉框
            this.cameraSelect.innerHTML = '<option value="">选择摄像头...</option>';
            this.devices.forEach((device, index) => {
                const option = document.createElement('option');
                option.value = device.deviceId;
                option.text = device.label || `摄像头 ${index + 1}`;
                this.cameraSelect.appendChild(option);
            });

            // 如果有摄像头，优先选择 Logi 摄像头
            if (this.devices.length > 0) {
                // 查找 Logi 摄像头
                const logiCamera = this.devices.find(device => 
                    device.label && device.label.toLowerCase().includes('logi')
                );
                
                // 如果找到 Logi 摄像头就使用它，否则使用第一个摄像头
                const selectedCamera = logiCamera || this.devices[0];
                this.cameraSelect.value = selectedCamera.deviceId;
                await this.startCamera(selectedCamera.deviceId);
            }

            return true;
        } catch (error) {
            console.error('摄像头初始化失败:', error);
            return false;
        }
    }

    async startCamera(deviceId) {
        try {
            // 如果已经有流在运行，先停止它
            if (this.stream) {
                this.stop();
            }

            // 使用选定的设备ID启动摄像头
            this.stream = await navigator.mediaDevices.getUserMedia({
                video: {
                    deviceId: { exact: deviceId },
                    width: { ideal: 1280 },
                    height: { ideal: 720 },
                    frameRate: { ideal: 30 }
                }
            });
            this.videoElement.srcObject = this.stream;
            return true;
        } catch (error) {
            console.error('启动摄像头失败:', error);
            return false;
        }
    }

    stop() {
        if (this.stream) {
            this.stream.getTracks().forEach(track => track.stop());
            this.stream = null;
            this.videoElement.srcObject = null;
        }
    }
}

// VideoRecorder 类
class VideoRecorder {
    constructor(stream) {
        this.stream = stream;
        this.mediaRecorder = null;
        this.chunks = [];
        
        // 设置录制选项
        const options = {
            mimeType: 'video/webm',  // 使用基础的 webm 类型
            videoBitsPerSecond: 1000000  // 1Mbps
        };
        
        try {
            this.mediaRecorder = new MediaRecorder(this.stream, options);
            console.log('MediaRecorder 创建成功，使用配置:', options);
        } catch (e) {
            console.error('创建 MediaRecorder 失败:', e);
            // 如果失败，尝试使用默认配置
            this.mediaRecorder = new MediaRecorder(this.stream);
            console.log('使用默认 MediaRecorder 配置');
        }
        
        this.mediaRecorder.ondataavailable = (e) => {
            if (e.data.size > 0) {
                this.chunks.push(e.data);
                console.log('收到数据块，大小:', e.data.size, 'bytes');
            }
        };
    }

    start() {
        try {
            this.chunks = [];
            this.mediaRecorder.start(1000); // 每秒生成一个数据块
            console.log('开始录制');
            return true;
        } catch (error) {
            console.error('录制开始失败:', error);
            return false;
        }
    }

    async stop() {
        return new Promise((resolve) => {
            this.mediaRecorder.onstop = async () => {
                const blob = new Blob(this.chunks, { type: 'video/webm' });
                console.log('视频大小:', blob.size, 'bytes');
                console.log('视频类型:', blob.type);
                console.log('视频块数量:', this.chunks.length);
                resolve(blob);
            };
            this.mediaRecorder.stop();
        });
    }

    async convertToMP4(webmBlob) {
        // 这里可以添加视频格式转换逻辑
        // 由于浏览器限制，直接返回原始格式
        return webmBlob;
    }
}

// HistoryManager 类
class HistoryManager {
    constructor(resultList) {
        this.resultList = resultList;
    }

    addEntry(text, type = 'success') {
        const entry = document.createElement('div');
        entry.className = `result-entry ${type}`;
        entry.textContent = text;
        this.resultList.insertBefore(entry, this.resultList.firstChild);
    }
}

// UIManager 类
class UIManager {
    constructor(startBtn, stopBtn, timerElement) {
        this.startBtn = startBtn;
        this.stopBtn = stopBtn;
        this.timerElement = timerElement;
        this.timerInterval = null;
    }

    updateButtonState(isRecording) {
        this.startBtn.disabled = isRecording;
        this.stopBtn.disabled = !isRecording;
    }

    startTimer() {
        let timeLeft = 20;
        this.timerElement.textContent = timeLeft;
        
        this.timerInterval = setInterval(() => {
            timeLeft--;
            this.timerElement.textContent = timeLeft;
            if (timeLeft <= 0) {
                this.stopTimer();
                stopRecording();
            }
        }, 1000);
    }

    stopTimer() {
        if (this.timerInterval) {
            clearInterval(this.timerInterval);
            this.timerInterval = null;
        }
        this.timerElement.textContent = '20';
    }
}

// APIClient 类
class APIClient {
    async processVideo(videoBlob, textPrompt) {
        const formData = new FormData();
        console.log('准备上传视频:');
        console.log('- 大小:', videoBlob.size, 'bytes');
        console.log('- 类型:', videoBlob.type);
        formData.append('file', videoBlob, 'video.webm');
        formData.append('text_prompt', textPrompt);

        console.log('开始发送视频到服务器...');
        const response = await fetch('/upload_video', {
            method: 'POST',
            body: formData
        });

        console.log('服务器响应状态:', response.status);
        const result = await response.json();
        console.log('服务器响应JSON:', result);
        
        if (!response.ok) {
            throw new Error(result.error || '服务器错误');
        }

        if (!result.success) {
            console.error('处理失败:', result.error);
            throw new Error(result.error || '视频处理失败');
        }

        // 检查数据结构中的text字段
        let resultText = '';
        if (result.text) {
            resultText = result.text;
        } else if (result.data && result.data.text) {
            resultText = result.data.text;
        }

        if (!resultText) {
            console.error('响应文本为空');
            throw new Error('视频处理失败：响应文本为空');
        }

        console.log('视频处理成功，文本结果:', resultText);
        return {...result, text: resultText};
    }
}

// StateManager 类
class StateManager {
    constructor() {
        this.isRecording = false;
        this.isProcessing = false;
        this.listeners = new Map();
    }

    setRecording(value) {
        this.isRecording = value;
        this.notifyListeners('recording', value);
    }

    setProcessing(value) {
        this.isProcessing = value;
        this.notifyListeners('processing', value);
    }

    on(event, callback) {
        if (!this.listeners.has(event)) {
            this.listeners.set(event, new Set());
        }
        this.listeners.get(event).add(callback);
    }

    notifyListeners(event, value) {
        const callbacks = this.listeners.get(event);
        if (callbacks) {
            callbacks.forEach(callback => callback(value));
        }
    }
}

// ErrorHandler 类
class ErrorHandler {
    static async handleError(error, uiManager) {
        console.error('错误:', error);
        uiManager.stopTimer();
        uiManager.updateButtonState(false);
        alert(error.message);
    }
}

// DOM元素
const videoElement = document.getElementById('videoElement');
const cameraSelect = document.getElementById('cameraSelect');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const timerElement = document.getElementById('timer');
const textPrompt = document.getElementById('textPrompt');
const resultList = document.getElementById('resultList');

// 初始化管理器
const cameraManager = new CameraManager(videoElement, cameraSelect);
const uiManager = new UIManager(startBtn, stopBtn, timerElement);
const historyManager = new HistoryManager(resultList);
const apiClient = new APIClient();
const stateManager = new StateManager();

let videoRecorder = null;

// 摄像头选择事件监听
cameraSelect.addEventListener('change', async (e) => {
    if (e.target.value) {
        await cameraManager.startCamera(e.target.value);
    }
});

// 开始录制
async function startRecording() {
    try {
        if (!cameraManager.stream) {
            const success = await cameraManager.startCamera(cameraSelect.value);
            if (!success) {
                throw new Error('无法访问摄像头，请确保已授予权限。');
            }
        }
        
        if (!videoRecorder) {
            videoRecorder = new VideoRecorder(cameraManager.stream);
        }
        
        if (videoRecorder.start()) {
            stateManager.setRecording(true);
            uiManager.updateButtonState(true);
            uiManager.startTimer();
        } else {
            throw new Error('开始录制失败，请刷新页面重试。');
        }
    } catch (error) {
        await ErrorHandler.handleError(error, uiManager);
    }
}

// 停止录制
async function stopRecording() {
    try {
        if (!videoRecorder) return;
        
        const videoBlob = await videoRecorder.stop();
        if (videoBlob) {
            stateManager.setRecording(false);
            uiManager.stopTimer();
            uiManager.updateButtonState(false);
            await processVideo(videoBlob);
        } else {
            throw new Error('停止录制失败，请刷新页面重试。');
        }
    } catch (error) {
        await ErrorHandler.handleError(error, uiManager);
    }
}

// 处理视频
async function processVideo(videoBlob) {
    if (stateManager.isProcessing) return;
    
    stateManager.setProcessing(true);
    try {
        console.log('开始处理视频...');
        const result = await apiClient.processVideo(videoBlob, textPrompt.value);
        console.log('视频处理结果:', result);
        
        if (result.text) {
            historyManager.addEntry(`处理完成 (${result.process_time}): ${result.text}`);
            console.log('结果已添加到历史记录');
        } else {
            historyManager.addEntry(`处理完成 (${result.process_time}): 视频处理成功但无文本结果`, 'warning');
        }
    } catch (error) {
        console.error('处理视频出错:', error);
        historyManager.addEntry(`处理失败: ${error.message}`, 'error');
    } finally {
        stateManager.setProcessing(false);
    }
}

// 清理资源
function cleanup() {
    cameraManager.stop();
    if (videoRecorder) {
        videoRecorder.stop();
        videoRecorder = null;
    }
    uiManager.stopTimer();
    stateManager.setProcessing(false);
    stateManager.setRecording(false);
    uiManager.updateButtonState(false);
}

// 事件监听
startBtn.addEventListener('click', startRecording);
stopBtn.addEventListener('click', stopRecording);

// 状态监听
stateManager.on('processing', (isProcessing) => {
    uiManager.updateButtonState(isProcessing);
});

stateManager.on('recording', (isRecording) => {
    if (!isRecording) {
        uiManager.updateButtonState(false);
    }
});

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    cameraManager.init();
});

// 页面卸载时清理
window.addEventListener('beforeunload', cleanup); 